﻿using KAKA.Domain;
using KAKA.Repository;
using Morus;
using System.Web;
using System.Web.Mvc;

namespace KAKA
{
    public class CurrentUserAttribute : FilterAttribute, IAuthorizationFilter
    {
        public CurrentUserAttribute()
        {
            Order = 2;
        }

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated)
            {
                User user = httpContext.Items[typeof(User)] as User;

                httpContext.Items[typeof(Member)] = user.Member.Nickname;
            }
        }

        public void OnAuthorization(AuthorizationContext filterContext)
        {
            var httpContext = filterContext.HttpContext;

            if (httpContext.User.Identity.IsAuthenticated)
            {
                User user = httpContext.Items[typeof(User)] as User;

                if (user == null)
                {
                    user = IoC.Resolve<IUserRepository>().Get(httpContext.User.Identity.Name);

                    if (user != null)
                    {
                        httpContext.Items[typeof(User)] = user;
                    }
                }
            }
        }
    }
}